package com.lwj.mallchat.common.common.exception;

import com.lwj.mallchat.common.common.domain.enums.CommonErrorEnum;
import com.lwj.mallchat.common.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lwj
 * @ClassName GlobalExceptionHandler
 * @date 2024/10/20 16:19
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        System.out.println();
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> {
            sb.append(x.getField()).append(x.getDefaultMessage()).append(",");
        });
        String msg = sb.substring(0, sb.length() - 1);
        return ApiResult.fail(CommonErrorEnum.PARAM_INVALID);
    }

    @ExceptionHandler(value = BusinessException.class)
    public ApiResult<?> businessException(BusinessException e) {
        log.info("business exception! The reason is:{}", e.getErrorMsg());
        return ApiResult.fail(e.getErrorCode(),e.getErrorMsg());
    }

    @ExceptionHandler(value = Throwable.class)
    public ApiResult<?> throwable(Exception e) {
        log.error("system exception! The reason is:{}", e.getMessage(),e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
    }
}
